package org.bigtree.example.common.frame.interceptor;

import cn.hutool.core.util.IdUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author bigTree
 * @since 2025/6/14
 */
@Slf4j
public class RequestTraceFilter implements HandlerInterceptor {
    private static final String LOG_TRACE_NAME = "traceId";
    private static final String OFFSET_TIME_NAME = "offsetTime";
    private static final ThreadLocal<Long> THREAD_LOCAL = new ThreadLocal<>();
    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        MDC.put(LOG_TRACE_NAME, IdUtil.fastSimpleUUID());
        THREAD_LOCAL.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) {
        String sb = STR."Request Url:\{request.getRequestURI()} -> [\{System.currentTimeMillis() - THREAD_LOCAL.get()} ms]";
        log.info(sb);
        THREAD_LOCAL.remove();
        MDC.clear();
    }
}
